Page({
  data: {
    fileName: '',
    filePath: ''
  },

  onLoad() {
    // 检查是否登录
    if (!getApp().globalData.isLogin) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
    }
  },

  // 选择本地Excel文件
  chooseFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['xlsx', 'xls'],
      success: (res) => {
        const file = res.tempFiles[0]
        this.setData({
          fileName: file.name,
          filePath: file.path
        })
      }
    })
  },

  // 从微信会话选择文件
  chooseMessageFile() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      extension: ['xlsx', 'xls'],
      success: (res) => {
        const file = res.tempFiles[0]
        this.setData({
          fileName: file.name,
          filePath: file.path
        })
      }
    })
  },

  // 上传文件到云存储
  async uploadFile() {
    if (!this.data.filePath) {
      wx.showToast({
        title: '请先选择文件',
        icon: 'none'
      })
      return
    }

    wx.showLoading({
      title: '上传中...'
    })

    try {
      // 上传文件到云存储
      const cloudPath = `excel/${Date.now()}-${this.data.fileName}`
      const uploadRes = await wx.cloud.uploadFile({
        cloudPath,
        filePath: this.data.filePath
      })

      // 调用云函数处理Excel文件
      const res = await wx.cloud.callFunction({
        name: 'processExcel',
        data: {
          fileID: uploadRes.fileID
        }
      })

      if (res.result.success) {
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        })
        
        // 跳转到分析页面
        wx.navigateTo({
          url: '/pages/analysis/analysis'
        })
      } else {
        throw new Error('处理失败')
      }
    } catch (error) {
      console.error('上传失败', error)
      wx.showToast({
        title: '上传失败，请重试',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  }
}) 